const mongoose = require('mongoose');
const Product = require('../models/product.model');

//新增
exports.create=function(req,res,next){
    const product = new Product(req.body);
    product.save().then((data)=>{
        res.json(data);
    })
}

exports.update=function(req,res,next){
    const id = req.params.id;
    Product.findByIdAndUpdate(id,{$set:req.body},{new:false}).then(data=>{
        res.json(data);//这里返回的是修改前的数据，不是修改后的。
    })
}


exports.remove=function(req,res,next){
    const id = req.params.id;
    Product.findByIdAndDelete(id,(err,data)=>{
        res.json(data);
    })
}

exports.list=function(req,res,next){
    var page = req.body.page?req.body.page:1;
    var rows = req.body.rows?req.body.rows:5;

    if(req.body.name && req.body.name.trim().length>0){                 name       = req.body.name;
            var str            = '(.*)'+name+'(.*)';
                queryCondition = {
                "name": new RegExp(str,'g')
            }
    }else{
             //显示全部数据
            name           = req.body.name;
            queryCondition = {
                "name": new RegExp(name,'i')
            }
    }
    Product.paginate(queryCondition,{page: + page,limit: + rows},function(err,result){
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    })
}



exports.getdata=function(req,res,next){
    var id = req.params.id;
    Product.findById(id).then(data=>{
        res.json(data);
    })
}

exports.removes=function(req,res,next){
    var ids = req.body.ids.split(',');
    if(ids.length>0){
        Product.remove({_id:{$in:ids}}).then(data=>{
            res.json({'message':'delete ok',status:200})
        })
    }

}

exports.catepro_0=function(req,res,next){   //数码电器
    var type = req.params.type;
    Product.find({"type":"13"}).then(data=>{
        res.json(data);
    })
}

exports.catepro_1=function(req,res,next){   //工业电器
    var type = req.params.type;
    Product.find({"type":"12"}).then(data=>{
        res.json(data);
    })
}

exports.catepro_2=function(req,res,next){   //家用电器
    var type = req.params.type;
    Product.find({"type":"11"}).then(data=>{
        res.json(data);
    })
}

exports.catepro_3=function(req,res,next){   //日用品
    var type = req.params.type;
    Product.find({"type":"21"}).then(data=>{
        res.json(data);
    })
}

exports.catepro_4=function(req,res,next){   //饮食用品
    var type = req.params.type;
    Product.find({"type":"22"}).then(data=>{
        res.json(data);
    })
}//cryppo

exports.catepro_5=function(req,res,next){   //交通出行用品
    var type = req.params.type;
    Product.find({"type":"23"}).then(data=>{
        res.json(data);
    })
}